import React, { useState, useEffect, useMemo, useCallback } from 'react'
import { Col, Form, Input, Button, Table, Modal, Switch, message, } from 'antd'
import { PageHeaderWrapper } from '@ant-design/pro-layout'
import RenderButtom from '@/components/RenderButton'
import SearchBox from '@/components/SearchBox'
import {
  fetchIndustry,
  addIndustry,
  delIndustry,
} from '@/services/platform/industry'
import { formItemLayout } from '@/utils/utils'
import { connect } from 'dva'

const hasSearchBtn = JSON.parse(localStorage.getItem('hasSearchBtn'))
const columns = [
  {
    title: '序号',
    dataIndex: 'sort',
    key: 'sort',
    render(text, record, index){
      return <div>{index + 1}</div>
    }
  },
  {
    title: '行业名称',
    dataIndex: 'catName',
    key: 'catName',
  },
  {
    title: '分类状态',
    dataIndex: 'catStatus',
    key: 'catStatus',
    render: t => <>{t == 1 ? '开启' : '关闭'}</>
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
];
const IndustryList = props => {
  const { form, platform, } = props
  const { inform } = platform
  const { getFieldDecorator } = form
  const [data, setData] = useState([])
  const [total, setTotal] = useState(null)
  const [record, setRecord] = useState([])
  const [visible, setVisible] = useState(false)

  useEffect(() => {
    init()
  }, [])

  const init = useCallback(async params => {
    const res = await fetchIndustry(params)
    setData(res.data)
    setTotal(res.total)
  }, [data])

  const addData = async params => {
    const res = await addIndustry(params)
    res.code == 0 && init()
    message.info(res.msg)
  }

  const delData = async params => {
    const res = await delIndustry(params)
    if (res.code == 0) {
      const index = data.findIndex(e => e.id == record.id);
      setData(() => {
        data.splice(index, 1);
        return [...data];
      });
    }
  }

  // 表单查询
  const handleSearch = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      console.log('Received values of form: ', values)

    })
  }
  // 表单清空
  const handleReset = e => {
    form.resetFields();
  }
  // 查询条件
  const getFields = () => {
    return(
      <Col span={8}>
        <Form.Item label={`名称`}>
          {getFieldDecorator(`mingcheng`, {})
            (<Input />)}
        </Form.Item>
      </Col>
    )
  }
  // 按钮处理
  const handleBtn = type => {
    switch (type) {
      // 新增
      case 1:
        return handleStatus()
      case 3:
        return handleStatus(record[0])
      case 4:
        return delData({
          id: record[0].id
        })
      default:
        break;
    }
  }

  const handleStatus = useCallback(record => {
    setVisible(!visible);
    props.dispatch({
      type: 'platform/update',
      payload: {
        inform: record,
      },
    });
  }, [visible]);

  // 新增编辑
  const modalConfirm = e => {
    e.preventDefault()
    form.validateFields((err, values) => {
      // console.log('Received values of form: ', inform)
      const params = {
        ...inform,
        ...values,
        catStatus: !values.catStatus ? '1' : '0',
      }
      addData(params).then(() => {
        setVisible(!visible)
      })
    })
  }

  const pagination = {
    total: parseInt(total),
    onChange(page) {
      init({
        pageNo: page,
        pageSize: 10,
      })
    }
  } 
  const rowSelection = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
      setRecord(selectedRows)
    },
  };

  return (
    <PageHeaderWrapper>
      <SearchBox handleReset={handleReset} handleSearch={handleSearch} getFields={getFields} />
      <RenderButtom click={handleBtn} />
      <Table 
        columns={columns}
        dataSource={hasSearchBtn ? data : []}
        rowKey={record => record.id}
        pagination={pagination}
        rowSelection={rowSelection}
      />
      <Modal
        title='新增/编辑'
        visible={visible}
        onOk={modalConfirm}
        onCancel={() => setVisible(!visible)}
      >
        <Form {...formItemLayout}>
          <Form.Item label="行业名称">
            {getFieldDecorator('catName', {
              initialValue: inform && inform.catName,
              rules: [
                {
                  required: true,
                },
              ],
            })(<Input />)}
          </Form.Item>
          <Form.Item label="是否启用">
            {getFieldDecorator('catStatus', {
              initialValue: inform && inform.catStatus == 1 ? true : false,
              valuePropName: 'checked',
            })(<Switch />)}
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
    )
}

export default connect(({ platform }) => ({
  platform,
}))(Form.create()(IndustryList))
